﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using Microsoft.Web.Administration;
using RestSharp;

namespace AppPoolCheckerService
{
    public partial class Service1
    {
        private PoolChecker poolChecker;

        public Service1()
        {

        }

        public void Start()
        {
            poolChecker = new PoolChecker();
        }

        public void Stop()
        {
            if (poolChecker != null)
            {
                poolChecker.Stop();
            }
        }

        private class PoolChecker
        {
            #region private static List<string> PoolNames
            /// <summary>
            /// Gets the Pools of the PoolChecker
            /// </summary>
            /// <value></value>
            private static List<string> PoolNames
            {
                get
                {
                    if (_pools == null)
                    {
                        _pools = new List<string>();
                        string str = ConfigurationManager.AppSettings["Pools"];
                        if (string.IsNullOrEmpty(str))
                        {
                            return _pools;
                        }
                        string[] strings = str.Split(',');
                        foreach (string s in strings)
                        {
                            if (string.IsNullOrWhiteSpace(s))
                            {
                                continue;
                            }
                            string ss = s.Trim();
                            if (string.IsNullOrEmpty(ss))
                            {
                                continue;
                            }
                            _pools.Add(ss);
                        }
                    }
                    return _pools;
                }
            }

            private static List<string> _pools;


            private static List<string> SiteNames
            {
                get
                {
                    if (_sites == null)
                    {
                        _sites = new List<string>();
                        string str = ConfigurationManager.AppSettings["Sites"];

                        if (string.IsNullOrEmpty(str))
                        {
                            return _sites;
                        }
                        string[] strings = str.Split(',');
                        foreach (string s in strings)
                        {
                            if (string.IsNullOrWhiteSpace(s))
                            {
                                continue;
                            }
                            string ss = s.Trim();
                            if (string.IsNullOrEmpty(ss))
                            {
                                continue;
                            }
                            _sites.Add(ss);
                        }
                    }

                    return _sites;
                }
            }

            private static List<string> _sites;


            #endregion
            private bool stop;

            public PoolChecker()
            {
                Thread t = new Thread(Run);
                t.Start();
            }
            public void Stop()
            {
                Log("Stop called");
                stop = true;
            }
            private void Run()
            {

                List<string> sites = new List<string>();

                foreach (string siteName in SiteNames)
                {
                    sites.Add(siteName);
                }

                if (sites.Count == 0)
                {
                    return;
                }

                Log(string.Format("Starting with {0} sites", sites.Count));

                while (true)
                {
                    if (stop)
                    {
                        Log("Stopping");
                        return;
                    }

                    for (int i = 0; i < sites.Count; i++)
                    {
                        string site = sites[i];

                        try
                        {   
                            var client = new RestClient(site);
                            var request = new RestRequest(Method.GET);
                            var response = client.Execute(request);

                            Log(string.Format("Started site {0}", site));
                        }
                        catch (Exception ex)
                        {   
                            Log(string.Format("Failed to start site {0}: {1}", site, ex.Message));
                        }

                        if (stop)
                        {
                            Log("Stopping");
                            return;
                        }
                        
                    }

                    Thread.Sleep(1000 * 60);

                }
                
            }
            private static void Log(string message)
            {
                try
                {
                    var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");

                    if (System.IO.Directory.Exists(dir) == false)
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }

                    string path = Path.Combine(dir, DateTime.Now.ToString("yyyy-MM-dd") + ".log");

                    File.AppendAllText(path, string.Format("{0}\t{1}{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message, Environment.NewLine));
                }
                catch { }
            }
        }
    }
}
